package com.yuanduo_app

import android.content.Context
import android.content.res.Resources
import android.util.TypedValue

/**
 * 尺寸扩展类
 */

/**
 * 获取屏幕宽度
 */
val Context.screenWidth
    get() = resources.displayMetrics.widthPixels

/**
 * 获取屏幕高度
 */
val Context.screenHeight
    get() = resources.displayMetrics.heightPixels


/**
 * float 转dp
 */
inline fun <reified T> Float.dp(): T {
    val result = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, this,
        Resources.getSystem().displayMetrics
    )

    return when (T::class) {
        Float::class -> result as T
        Int::class -> result.toInt() as T
        else -> throw IllegalStateException("Type not supported")
    }
}
/**
 * dp单位，自动转换成对应像素
 */
inline fun <reified T> Int.dp(): T {
    val result = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, this.toFloat(),
        Resources.getSystem().displayMetrics
    )

    return when (T::class) {
        Float::class -> result as T
        Int::class -> result.toInt() as T
        else -> throw IllegalStateException("Type not supported")
    }
}




/**
 * sp单位自动转换成像素
 */
inline fun <reified T> Int.sp(): T {
    val result = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP, this.toFloat(),
        Resources.getSystem().displayMetrics
    )

    return when (T::class) {
        Float::class -> result as T
        Int::class -> result.toInt() as T
        else -> throw IllegalStateException("Type not supported")
    }
}
